package com.cqan.report.controller;

import static com.cqan.common.ViewName.*;

import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqan.common.ExportUtils;
import com.cqan.controller.BaseController;
import com.cqan.entity.Atom;
import com.cqan.entity.AtomField;
import com.cqan.entity.Report;
import com.cqan.exception.AppException;
import com.cqan.manager.ReportManager;
import com.cqan.orm.Page;

@Controller
@RequestMapping("/report")
public class ReportController extends BaseController<Report> {

	@Resource
	private ReportManager reportManager;
	
	@RequestMapping("/list.htm")
	public ModelAndView list(Integer pageNo,HttpServletRequest request) throws AppException{
		ModelAndView mav = new ModelAndView(REPORT_LIST);
		List<Report> reports = reportManager.reportList();
		JSONArray arr = new JSONArray(reports.size()+1);
		JSONObject obj = new JSONObject();
		obj.put("id", "1");
		obj.put("pId", "0");
		obj.put("name", "报表");
		obj.put("iconSkin", "pIcon01");
		arr.add(obj);
		for (Report report : reports) {
			JSONObject json = new JSONObject();
			json.put("id", report.getId()+1);
			json.put("pId", "1");
			json.put("name",report.getName());
			json.put("iconSkin","icon06");
			arr.add(json);
		}
		mav.addObject("reports", arr.toJSONString());
		return mav;
	}
	
	@RequestMapping("/reportData.htm")
	public ModelAndView reportData(Long rid,Integer pageNo){
		ModelAndView mav = new ModelAndView(REPORT_DATA);
		List<AtomField> fields = reportManager.reportFields(rid);
		Page<Atom> page = new Page<Atom>(20);
		page = reportManager.reportAtoms(rid, page);
		mav.addObject("page", page);
		mav.addObject("fields", fields);
		return mav;
	}
	
	@RequestMapping("/export.htm")
	public String export(Long rid,HttpServletResponse response) throws AppException{
		try {
			Report report = reportManager.getReport(rid);
			List<AtomField> fields = reportManager.reportFields(rid);
			Page<Atom> page = new Page<Atom>(20);
			page = reportManager.reportAtoms(rid, page);
			response.setContentType("application/vnd.ms-excel");
			String fileName = new String(report.getName().getBytes("UTF-8"),"ISO8859_1");
	    	response.setHeader("Content-Disposition", "attachment;fileName="+fileName+".xls");  
	        OutputStream os=response.getOutputStream();  
			ExportUtils.export(report, fields, page.getResult(), os);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException();
		}
		
		return null;
	}
}
